#! /usr/bin/env python
# coding=utf8

from BeautifulSoup import BeautifulSoup
from urllib import urlencode
import urllib2
from sys import argv

class main:
    """main class"""
    def __init__(self, task, info):
        """do all things here"""
        # set the poster name
        self.poster = "RAh-XePhON"
        # set the paste url
        self.url = 'http://paste.ubuntu.org.cn/'
        # set the HTTP header data
        self.header_data = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; zh-TW; rv:1.8.1.11) Gecko/200711    27 Firefo    x/2.0.0.11)', 'Referer': 'http://paste.ubuntu.org.cn/ '}
        # first, notice that what should do
        if task == 'view':
            # should get the data from paste
            # parse the HTML data, call self.viewFeed
            if info.isdigit():
                self.viewFeed(info)
            else:
                print "ID should be all digital number"
        elif task == 'paste':
            # or should paste the data to paste
            # directly paste 
            self.pasteFeed(info)
        elif task == 'list':
            # list the news posts
            self.listFeed()

    def viewFeed(self, key_id):
        """view the data from paste"""
        # the post url is paste's url plus post id
        url = self.url + key_id
        # make the request, open the url and read the data
        request = urllib2.Request(url, None, self.header_data)
        # try to open the url and get the data
        try:
            html_page = urllib2.urlopen(request)
            html = html_page.read()
            html_page.close()
        except urllib2.URLError, e:
            print "Open URL Error, please check your network state"
        # open url successful
        print "Opened this page: %s" % html_page.geturl()
        if len(html):
            soup = BeautifulSoup(html)
            # get the contect data
            content =  soup.textarea.string
            if content:
                print content
            else:
                print "Can not found any data, maybe input a wrong ID"

    def pasteFeed(self, info):
        """paste the data to paste"""
        # encode the data
        data = urlencode([("parent_pid", ''),
                          ("poster", self.poster),
                          ("paste", ''),
                          ("class", 'actionscript'),
                          ('screenshot', ''),
                          ("code2", info)])
        # creat a request which attached the data and send it to server
        request = urllib2.Request(self.url, data, self.header_data)
        html_page = urllib2.urlopen(request)
        # get the the url that data was pasted
        paste_at = html_page.geturl()
        print "Paste @ %s" % paste_at
        # close session
        html_page.close()

    def listFeed(self):
        """list the news post at paste"""
        # make a request
        request = urllib2.Request(self.url, None, self.header_data)
        # try to open the url, and get the data from it
        try:
            html_page = urllib2.urlopen(request)
            html = html_page.read()
            html_page.close()
        except urllib2.URLError, e:
            print "Open URL Error, maybe your network have some problem"
        if len(html):
            # the news post list should inside a div that class is menu
            soup = BeautifulSoup(html)
            # get the div that id was menu, it should find only one element
            menu_list = soup("div", id='menu')[0]
        print "already get the list"
        # print out the list, because the first link and the list link is not the post, so they should not be displaied
        num = 0
        for i in menu_list("a"):
            # print the author - ID
            # do not display the first link and the last link, the list should have 6 posts' id
            if num and num <= 6:
                print "%10s  -  %s" % (i.string, i['href'][1:])
            num += 1


if __name__ == "__main__":
    if len(argv) == 3:
        task = argv[1]
        info = argv[2]
    else:
        task = raw_input("do what? ")
        info = raw_input("need what? ")
    main(task, info)
